# -*- coding: utf-8 -*-
"""
Created on Fri Jan 11 08:29:28 2013

@author: nzhao
"""

from traits.api import HasTraits, Instance, Float, Button
from traitsui.api import View, Item, HGroup, VGroup, TextEditor

from chaco.api import Plot, PlotGraphicsContext
from chaco.tools.api import PanTool, ZoomTool

from enable.component_editor import ComponentEditor
from enable.api import BaseTool

from curves import MyArrayPlotData

class CursorTool(BaseTool):
    coordx = Float()
    coordy = Float()

    def normal_mouse_move(self, event):
        self.coordx, self.coordy = self.component.map_data((event.x, event.y))

    traits_view=View(
                    HGroup( 
                        Item('coordx', style = 'readonly', label = 'x = ', editor=TextEditor(format_str='%5.2f')),
                        Item('coordy', style = 'readonly', label = 'y = ', editor=TextEditor(format_str='%5.2f')),
                        )
                    )
        
class DataViewer(HasTraits):

    fig  = Instance(Plot)
    data = Instance(MyArrayPlotData, ())

    mouse_xy = Instance(CursorTool)
    
    save_imag = Button('save')

    traits_view = View(
        HGroup(VGroup(
            Item('fig',editor=ComponentEditor(), show_label=False, width = 1000 ),
            HGroup(            
                Item('mouse_xy', label='mouse at ', style='custom'),
                Item('save_imag', label='save image'),
            ),
            show_border = True, label="Plot"
        ),
        Item('data',style='custom', width =200, show_label=False),
        layout='split'
        ),
        
        width=1200, height=800,
        resizable=True,
        title="Chaco Plot")

    def __init__(self):
        self.fig = Plot(self.data)
        self.replot()
        self.data.on_trait_change(self.replot, 'curve_num')
        
        self.mouse_xy = CursorTool(self.fig)

        self.fig.tools.append(self.mouse_xy)
        self.fig.tools.append(PanTool(self.fig))
        self.fig.tools.append(ZoomTool(self.fig))
        
    def replot(self):
        for curve in self.data.curves:
            if curve.type is 'line_scatter':
                self.fig.plot((curve.name+'_x', curve.name+'_y'), type='line', color=curve.color)
                self.fig.plot((curve.name+'_x', curve.name+'_y'), type='scatter', color=curve.color)
            else:
                self.fig.plot((curve.name+'_x', curve.name+'_y'), type=curve.type, color=curve.color)
        return
    
    def _save_imag_fired(self):
        container = self.fig
        size = container.outer_bounds
        print size
        container.do_layout(force=True)
        gc = PlotGraphicsContext(size, 72.0)
        gc.render_component(container)
        gc.save('output.png')





































